package example.util;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ServletUtil {
    public static String getInputString(InputStream input) throws IOException {
        StringBuilder result = new StringBuilder();
        BufferedReader reader = null;
        try {
            // 使用 BufferedReader 读取输入流
            reader = new BufferedReader(new InputStreamReader(input));
            char[] charBuffer = new char[1024];
            int bytesRead;
            while ((bytesRead = reader.read(charBuffer)) != -1) {
                result.append(charBuffer, 0, bytesRead);
            }
        } finally {
            // 关闭 BufferedReader
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result.toString();
    }

    public static  String getBodyData(HttpServletRequest request) {
        StringBuffer data = new StringBuffer();
        String line = null;
        BufferedReader reader = null;
        try {
            reader = request.getReader();
            while (null != (line = reader.readLine()))
                data.append(line).append('\n');
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        return data.toString();
    }

}
